package top.tungsword.webconsole.biz.service.login;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.tungsword.webconsole.biz.param.LoginParam;
import top.tungsword.webconsole.biz.response.WebReturnInfo;
import top.tungsword.webconsole.manager.i18n.I18nService;
import top.tungsword.webconsole.biz.service.base.BaseBiz;
import top.tungsword.webconsole.biz.util.CookieUtil;
import top.tungsword.webconsole.dal.entity.SsoUser;
import top.tungsword.webconsole.dal.mapper.SsoUserMapper;
import top.tungsword.webconsole.manager.cache.EhcacheLoginService;
import top.tungsword.webconsole.util.ParamCheckUtil;
import top.tungsword.webconsole.util.PasswordUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;

import static top.tungsword.webconsole.biz.constant.Constants.LOGIN_SESSION_ID;
import static top.tungsword.webconsole.biz.constant.I18nConstants.LOGIN_ERROR;
import static top.tungsword.webconsole.biz.constant.I18nConstants.LOGIN_LENGTH_ERROR;
import static top.tungsword.webconsole.biz.constant.I18nConstants.LOGIN_NULL_ERROR;

/**
 * @author chenji.yu
 * @date 2020/4/27 14:45
 * @description
 */
@Service
public class LoginBiz extends BaseBiz {
    @Autowired
    private SsoUserMapper ssoUserMapper;

    @Autowired
    private EhcacheLoginService ehcacheLoginService;

    @Autowired
    private I18nService i18nService;

    /**
     * 功能描述: <br>
     *     登录功能
     * @Param response
     * @Param loginParam
     * @Return top.tungsword.webconsole.biz.response.WebReturnInfo<java.lang.String>
     * @Author chenji.yu
     * @Date 2020/4/27 15:48
     */
    public WebReturnInfo<String> login(HttpServletResponse response, LoginParam loginParam){
        //入参check
        String message = checkParam(loginParam);
        if(StringUtils.isNotEmpty(message)){
            WebReturnInfo<String> webReturnInfo = WebReturnInfo.FAIL;
            webReturnInfo.setMessage(message);
            return webReturnInfo;
        }

        //登录密码check
        SsoUser ssoUser = ssoUserMapper.selectByUsername(loginParam.getUsername());

        if(null == ssoUser){
            //登录失败
            WebReturnInfo<String> webReturnInfo = WebReturnInfo.FAIL;
            webReturnInfo.setMessage(i18nService.getMessage(LOGIN_ERROR));
            return webReturnInfo;
        }

        String password = PasswordUtil.sha1(loginParam.getPassword());
        boolean isLogin = password.equals(ssoUser.getPassword());
        if(!isLogin){
            //登录失败
            WebReturnInfo<String> webReturnInfo = WebReturnInfo.FAIL;
            webReturnInfo.setMessage(i18nService.getMessage(LOGIN_ERROR));
            return webReturnInfo;
        }

        //登录成功，设置session和cookie
        String loginToken = createSession(loginParam.getUsername());
        //TODO 本地缓存存储用户信息
        ehcacheLoginService.put(loginToken, true);
        CookieUtil.set(response, LOGIN_SESSION_ID, loginToken);
        WebReturnInfo<String> webReturnInfo = WebReturnInfo.SUCCESS;
        logger.info("用户"+loginParam.getUsername()+"登录成功，session id为"+loginToken);
        //获取用户权限
        return webReturnInfo;
    }

    private String checkParam(LoginParam loginParam){
        //参数check
        StringBuffer message = new StringBuffer();
        ParamCheckUtil.notNullCheck(loginParam.getUsername(), i18nService.getMessage(LOGIN_NULL_ERROR), message);
        ParamCheckUtil.notNullCheck(loginParam.getPassword(), i18nService.getMessage(LOGIN_NULL_ERROR), message);
        ParamCheckUtil.lengthCheck(loginParam.getUsername(), 18, i18nService.getMessage(LOGIN_LENGTH_ERROR), message);
        return message.toString();
    }

    private String createSession(String username){
        //根据用户名和当前时间生成sessionId
        String sessionStr = username + System.currentTimeMillis();
        return new BigInteger(sessionStr.getBytes()).toString(16);
    }

    /**
     * 功能描述: <br>
     *     退出登录信息
     * @Param request
     * @Param response
     * @Return void
     * @Author chenji.yu
     * @Date 2020/4/29 16:15
     */
    public void logout(HttpServletRequest request, HttpServletResponse response){
        String sessionId = CookieUtil.getValue(request, LOGIN_SESSION_ID);
        CookieUtil.remove(request, response, LOGIN_SESSION_ID);
        ehcacheLoginService.remove(sessionId);
        logger.info("session id："+sessionId+"用户登录，并且清除缓存和cookie");
    }
}
